package org.jeecg.modules.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.modules.common.mapper.CommonMethodMapper;
import org.jeecg.modules.common.service.CommonMethodService;
import org.jeecg.modules.constant.BikeConstant;
import org.jeecg.modules.param.area.entity.BikeSysArea;
import org.jeecg.modules.param.area.mapper.BikeSysAreaMapper;
import org.jeecg.modules.param.member.entity.BikeMemberUser;
import org.jeecg.modules.param.member.mapper.BikeMemberUserMapper;
import org.jeecg.modules.param.pile.entity.BikePile;
import org.jeecg.modules.param.pile.mapper.BikePileMapper;
import org.jeecg.modules.param.station.entity.BikeStation;
import org.jeecg.modules.param.station.mapper.BikeStationMapper;
import org.jeecg.modules.param.sysparam.entity.BikeSysParam;
import org.jeecg.modules.param.sysparam.mapper.BikeSysParamMapper;
import org.jeecg.modules.system.announcement.entity.BikeAnnouncement;
import org.jeecg.modules.system.announcement.mapper.BikeAnnouncementMapper;
import org.jeecg.modules.system.messagelog.entity.BikeSysMessageLog;
import org.jeecg.modules.system.messagelog.mapper.BikeSysMessageLogMapper;
import org.jeecg.modules.system.send.entity.BikeAnnouncementSend;
import org.jeecg.modules.system.send.mapper.BikeAnnouncementSendMapper;
import org.jeecg.modules.system.upgrade.entity.BikeUpgradeAppPackage;
import org.jeecg.modules.utils.BikeResult;
import org.jeecg.modules.utils.RandomCodeUtils;
import org.jeecg.modules.utils.SMSDmeo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 公共方法
 * 月月鸟
 */
@Service
public class CommonMethodServiceImpl implements CommonMethodService {
    @Resource
    private CommonMethodMapper commonMethodMapper;
    /**
     * 系统参数表
     * */
    @Resource
    private BikeSysParamMapper bikeSysParamMapper;

    @Resource
    private BikePileMapper bikePileMapper;

    @Resource
    private BikeSysAreaMapper bikeSysAreaMapper;

    @Resource
    private BikeStationMapper bikeStationMapper;
    @Resource
    private BikeMemberUserMapper bikeMemberUserMapper;


    @Resource
    private BikeAnnouncementMapper bikeAnnouncementMapper;
    @Resource
    private BikeAnnouncementSendMapper bikeAnnouncementSendMapper;

    @Resource
    private BikeSysMessageLogMapper bikeSysMessageLogMapper;
    /**
     * 获取车桩或网点最新版本 文件
     * @param appCode
     * 100001 用户端android
     * 100002 用户端IOS
     * 100003 运维端android
     * 100004 硬件网点
     * 100005 硬件车桩
     * */
    public byte[] getNewEdition(String appCode) {
        BikeUpgradeAppPackage bikeUpgradeAppPackage=commonMethodMapper.getNewEditionByAppCode(appCode);
        if (bikeUpgradeAppPackage!=null&&bikeUpgradeAppPackage.getFileData()!=null&&bikeUpgradeAppPackage.getFileData().length!=0){
            return bikeUpgradeAppPackage.getFileData();
        }
        return null ;
    }
    /**
     *校验车桩编号
     * */
    @Override
    public BikeResult checkPileCode(String pileCodes) {
        String stationCode = pileCodes.substring(0, 5);
        String pileCode =pileCodes.substring(5,7);
        String checkCode = pileCodes.substring(7,11);
        BikeStation bikeStation = bikeStationMapper.selectOne(new QueryWrapper<BikeStation>().eq("code", stationCode));
        if (bikeStation==null){
            return BikeResult.error("0","无效的网点编号",null);
        }
        if (bikeStation.getIsRegister().equals(BikeConstant.y_n_no)){
            return BikeResult.error("0","网点未注册，请更换网点",null);
        }
        if (bikeStation.getStatus().equals(BikeConstant.y_n_no)){
            return BikeResult.error("0","网点未启用，请更换网点",null);
        }

        // 4：车桩校验
        QueryWrapper<BikePile> pileWrapper = new QueryWrapper<>();
        pileWrapper.eq("code",pileCode);
        pileWrapper.eq("station_id", bikeStation.getId());
        pileWrapper.eq("check_code", checkCode);
        BikePile bikePile = bikePileMapper.selectOne(pileWrapper);
        if (bikePile==null){
            return BikeResult.error("0","无效的车桩编号",null);
        }

        if (bikePile.getStatus().equals(BikeConstant.y_n_no)){
            return BikeResult.error("0","车桩未启用，请更换车桩",null);
        }
        if (bikePile.getIsLock().equals(BikeConstant.y_n_yes)){
            return BikeResult.error("0","车桩被锁定，请更换车桩",null);
        }
        return BikeResult.ok("1","有效编号",null);
    }
    /**
     *所有身份证 x改为X
     * */
    @Override
    public void updateIdCard() {
        List<BikeMemberUser> bikeMemberUsers = bikeMemberUserMapper.selectList(new QueryWrapper<BikeMemberUser>().like("id_card", "x"));
        for (BikeMemberUser tb : bikeMemberUsers){
            tb.setIdCard(tb.getIdCard().replace("x","X"));
            bikeMemberUserMapper.updateById(tb);
        }
    }



    /**
     * 根据 借还时间 计算费用
     * */
    @Override
    public String getCost(Date pickTime, Date stopTime) {
        //获取免费时间长
        BikeSysParam freeTimes = bikeSysParamMapper.selectOne(new QueryWrapper<BikeSysParam>().eq("p_name", "param008"));
        //分钟转毫秒
        long freeTime = Integer.parseInt(freeTimes.getPValue()) * 60000;
        //获取收费周期
        BikeSysParam cycleTimes = bikeSysParamMapper.selectOne(new QueryWrapper<BikeSysParam>().eq("p_name", "param009"));
        double cycleTime = Double.parseDouble(cycleTimes.getPValue()) * 60000;
        //获取每周期费用
        BikeSysParam cycleCosts = bikeSysParamMapper.selectOne(new QueryWrapper<BikeSysParam>().eq("p_name", "param010"));
        int cycleCost = Integer.parseInt(cycleCosts.getPValue());
        double newTime = stopTime.getTime() - pickTime.getTime() - (long) freeTime;
        if (newTime > 0) {
            //计算多少周期
            double time = newTime / cycleTime;
            //判断是否整数
            int s = (int) time;
            int a;
            //不为整数+1
            if (s == time) {
                a = (int) (time);

            } else {
                a = (int) (time + 1);
            }
            if (a <= 1) {
                return String.valueOf(a);
            } else {
                return String.valueOf(a * cycleCost - 2);
            }
        } else {
            return "0";
        }
    }
    /**
     * 获取指定区域的所有最下级区域 id
     * */
    public List<String> getChildArea(String id){
        List<String> areaIds= new ArrayList<>();
        List<BikeSysArea> bikeSysAreas = bikeSysAreaMapper.selectList(new QueryWrapper<BikeSysArea>()
                .select("id","parent_id","has_child","area_code")
                .eq("parent_id", id)
                .eq("status","1")
        );
        if (!bikeSysAreas.isEmpty()){
            //此区域非最下级
            for (BikeSysArea tb : bikeSysAreas){
                if (tb.getHasChild().equals("0")){
                    //下级区域无子节点
                    areaIds.add(tb.getId());
                }else {
                    //下级区域有子节点
                    List<String> childStation = getChildArea(tb.getId());
                    areaIds.addAll(childStation);
                }
            }
        }else {
            //此id就是最下级
            BikeSysArea sysArea = bikeSysAreaMapper.selectById(id);
            if (sysArea!=null){
                areaIds.add(sysArea.getId());
            }
        }
        return areaIds;
    }

    /**
     * 获取指定区域下级网点 id
     * */
    public List<String> getChildStation(String id) {
        ArrayList<String> list = new ArrayList<>();
        List<String> areaIds = getChildArea(id);
        if (!areaIds.isEmpty()) {
            List<BikeStation> stations = bikeStationMapper.selectList(new QueryWrapper<BikeStation>().select("id").in("area_id", areaIds).eq("status", BikeConstant.y_n_yes));
            for (BikeStation tb : stations) {
                list.add(tb.getId());
            }
        }else {
            BikeStation bikeStation = bikeStationMapper.selectById(id);
            if (bikeStation!=null){
                list.add(bikeStation.getId());
            }
        }
        return list;
    }
    /**
     * 返回付款短信内容
     * */

    /**
     * 付款短信提示
     * */
    @Override
    public void paySMS(String phone,String message) {
        BikeSysMessageLog newBikeSysMessageLog = new BikeSysMessageLog();
        newBikeSysMessageLog.setPhone(phone);
        newBikeSysMessageLog.setMessage(message);
        bikeSysMessageLogMapper.insert(newBikeSysMessageLog);
        SMSDmeo.sendMessage(phone,message);
    }

    @Override
    public String getPaySms(String cost) {
        String paySmsText = BikeConstant.pay_Sms_text;
        return paySmsText;
    }

    @Override
    public void paySysMessage(BikeAnnouncement bikeAnnouncement) {

    }
    /**
     * 新增个人系统消息
     *
     * @param userId 用户id
     * @param phone  手机号=账号
     * @param title  标题
     * @param msg    内容
     */
    @Override
    public void addSysMessages(String userId, String phone, String title, String msg) {
        BikeAnnouncement bikeAnnouncement = new BikeAnnouncement();
        //消息ID
        String baId = RandomCodeUtils.getUUID();
        bikeAnnouncement.setId(baId);
        //标题
        bikeAnnouncement.setTitile(title);
        //简述 为内容前6个字+...
        bikeAnnouncement.setDescription(msg.substring(0, 6) + "...");
        //内容
        bikeAnnouncement.setMsgContent(msg);

        bikeAnnouncement.setMsgType("USER");
        //发布时间
        bikeAnnouncement.setSendTime(new Date());
        //开始时间
        bikeAnnouncement.setStartTime(new Date());
        //消息类型
        bikeAnnouncement.setMsgCategory("2");
        //已发布
        bikeAnnouncement.setSendStatus("1");
        //不置顶
        bikeAnnouncement.setIsTop("0");
        //非删除状态
        bikeAnnouncement.setDelFlag("0");
        bikeAnnouncementMapper.insert(bikeAnnouncement);
        BikeAnnouncementSend bikeAnnouncementSend = new BikeAnnouncementSend();
        //消息id
        bikeAnnouncementSend.setAnntId(baId);
        //用户id
        bikeAnnouncementSend.setUserId(userId);
        //阅读状态
        bikeAnnouncementSend.setReadFlag("0");
        bikeAnnouncementSendMapper.insert(bikeAnnouncementSend);
    }

    /**
     * 根据消息模板编号 获取模板内容
     */
    @Override
    public String getMessageTemplateByCode(String code) {
        return commonMethodMapper.getMessageTemplateByCode(code);
    }



}
